package com.matrix.draft.sockettest.groupchatroom.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GroupChatClient {

    private ClientProperties properties;

    private Selector selector;

    private SocketChannel channel;

    private String username;

    private ExecutorService executorService;

    // 构造函数
    public GroupChatClient(String username) {
        try {
            properties = new ClientProperties();
            executorService = Executors.newSingleThreadExecutor();
            this.username = username;
            selector = Selector.open();
            channel = SocketChannel.open(new InetSocketAddress(properties.getHost(), properties.getPort()));
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            System.err.println(username + "主动连接上了服务器");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听事件
    public void listenEvent() {
        // 用一个线程处理Selector的事件
        executorService.execute(() -> {
            try {
                while (selector.select()>0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        /** OP_READ事件 **/
                        if (key.isReadable()) {
                            doRead(key);
                        }
                        iterator.remove();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }

    // 发送消息
    public void doSend(String msg) {
        try {
            msg = username + ": " + msg;
            channel.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取消息(接收广播来的消息)
    public void doRead(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int len = channel.read(buffer);
            if (len > 0) {
                System.out.println(new String(buffer.array(), 0, len, StandardCharsets.UTF_8));
            } else {
                System.out.println("len小于0");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
